Welcome to JavaScript!

6.20 构造函数添加属性和方法

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</title>

<script type="text/javascript">

//构造函数:主要功能初始化对象,可以想象成一套模板或一套方案;

//构造函数:通过new函数名来实现化对象的函数叫做构造函数;

//new就是在创建对象,从无到有,构造函数就是为初始化的对象添加属性和方法;

//构造函数首写为大写字母,一般规范如此;

function Ren(){

this.name=""; //this:表示现在还不知道,没有具体的名称;

this.sex="男";

this.age=40;

this.height=169;

this.benLing=function (){

alert("会做饭")

}

}

var laoLiu=new Ren(); //通过new方法来创建具体的叫"laoLiu"的人;

//通过new的方法创建具体的对象,this才有具体的名称,现在this就表示laoLiu;

laoLiu.name="老六";

laoLiu["age"]=38;

laoLiu.tuanYuan="共产党"

console.log(laoLiu);

________________________________________________________________

var xiaoZhang=new Ren();

xiaoZhang.benLing=function (){

alert("会做饭,会泡妞,会开车")

}

xiaoZhang.benLing();

xiaoZhang.aiHao=function (){

alert("唱歌")

}

xiaoZhang.aiHao();

</script>

</head>

<body>

</body>

</html>